<?php

namespace app\api\service;

use app\store\model\GroupOrder;
use think\facade\Db;

class GroupOrderService
{

    /**
     * 获取拼团订单列表
     * */
    public static function getGroupActivityList($user_id, $activity_status)
    {

        $query = Db::name('group_activity_record')
            ->field('a.group_goods_id,a.group_order_id,a.end_time,a.status,b.goods_name,b.image,b.market_price,b.sell_price,b.buy_num')
            ->alias('a')
            ->join('group_order_item b', 'a.group_order_id=b.group_order_id')
            ->withAttr('image', function ($value) {
                return request()->domain() . $value;
            })->withAttr('end_time', function ($value) {
            return date('Y-m-d H:i:s', $value);
        })->where('a.user_id', $user_id);

        if (!empty($activity_status)) {
            $query->where('status', $activity_status);
        }

        $orders = $query->paginate(10);

        return $orders;
    }

    /**
     * 获取用户参加活动记录
     * */
    public static function findUserGroupActivityRecord($user_id, $group_activity_id)
    {
        $id = Db::name('group_activity_record')->where(['user_id' => $user_id, 'group_activity_id' => $group_activity_id])->value('id');

        return $id;
    }

    /**
     * 获取拼团订单列表
     * */
    public static function getOrderList($uid, $param)
    {

        $query = GroupOrder::field('id,order_no,payment_type,discount_amount,is_after_sale,after_sale_status,real_amount,status')
            ->where('user_id', $uid)
            ->with('items');

        if (!empty($param['order_status'])) {
            $query->where('status', $param['order_status']);
        }

        $orders = $query->paginate(10);

        return $orders;
    }

    /**
     * 检查拼团人数是否已足够
     * */
    public static function checkGroupNum($group_activity_id)
    {
        $count = Db::name('group_activity_record')->where('group_activity_id', $group_activity_id)->count('id');

        return $count;
    }

    /**
     * 获取支付配置信息
     * */
    public static function findPaymentConfig($store_id, $type)
    {
        $paymentConfig = Db::name('payment_config')->where(['store_id' => $store_id, 'type' => $type])->value('config');

        if (empty($paymentConfig)) {
            return [];
        }
        return json_decode($paymentConfig, true);
    }

    /**
     *
     * 获取用户信息
     * */
    public static function getUserInfo($user_id)
    {
        $user = Db::name('user')->field('nickname,avatar,user_id')->where('user_id', $user_id)->find();

        return $user;
    }

    /**
     * 保存订单信息
     *
     * */
    public static function saveOrder($data)
    {
        $s_data = [
            'user_id' => $data['user_id'],
            'store_id' => $data['store_id'],
            'logistics_mode' => empty($data['logistics_mode']) ? '' : $data['logistics_mode'],
            'pick_point_id' => empty($data['pick_point_id']) ? '' : $data['pick_point_id'],
            'order_no' => $data['order_no'],
            'prepayment_amount' => isset($data['prepayment_amount']) ? $data['prepayment_amount'] : 0,
            'real_amount' => $data['real_amount'],
            'receiver_name' => empty($data['receiver_name']) ? '' : $data['receiver_name'],
            'receiver_phone' => empty($data['receiver_phone']) ? '' : $data['receiver_phone'],
            'province' => empty($data['province']) ? '' : $data['province'],
            'city' => empty($data['city']) ? '' : $data['city'],
            'county' => empty($data['county']) ? '' : $data['county'],
            'address' => empty($data['address']) ? '' : $data['address'],
            'remark' => !empty($param['remark']) ? $param['remark'] : '',
            'status' => 1,
            'create_time' => time(),
        ];
        if (!empty($data['logistics_mode']) && $data['logistics_mode'] == 2) {
            $is_pick_point = Db::name('pick_point')->where(['store_id' => $data['store_id'], 'status' => 1, 'id' => $data['pick_point_id'], 'delete_time' => 0])->find();
            $s_data['receiver_name'] = $is_pick_point['contact_name'];
            $s_data['receiver_phone'] = $is_pick_point['contact_phone'];
            $s_data['province'] = $is_pick_point['province'];
            $s_data['city'] = $is_pick_point['city'];
            $s_data['county'] = $is_pick_point['area'];
            $s_data['address'] = $is_pick_point['address'];
            $s_data['lat'] = $is_pick_point['lat'];
            $s_data['lng'] = $is_pick_point['lng'];
            $s_data['pick_name'] = $is_pick_point['name'];
        }
        $group_order_id = Db::name('group_order')->insertGetId($s_data);

        Db::name('group_order_item')->insert([
            'group_order_id' => $group_order_id,
            'group_goods_id' => $data['group_goods_id'],
            'goods_name' => $data['goods_name'],
            'attr' => !empty($data['attr']) ? $data['attr'] : '',
            'image' => $data['image'],
            'market_price' => $data['market_price'],
            'sell_price' => $data['sell_price'],
            'group_price' => $data['group_price'],
            'buy_num' => $data['buy_num'],
            'total_amount' => $data['real_amount'],
        ]);

        Db::name('group_order_trade')->insert([
            'store_id' => $data['store_id'],
            'group_order_id' => $group_order_id,
            'trade_method' => $data['payment_type'],
            'out_trade_no' => $data['out_trade_no'],
            'trade_fee' => $data['real_amount'],
            'trade_status' => -1,
        ]);

        Db::name('group_activity_record')->insert([
            'group_activity_id' => $data['group_activity_id'],
            'resell_session_id' => isset($data['resell_session_id']) ? $data['resell_session_id'] : 0,
            'group_order_id' => $group_order_id,
            'group_goods_id' => $data['group_goods_id'],
            'user_id' => $data['user_id'],
            'avatar' => $data['avatar'],
            'nickname' => $data['nickname'],
            'group_num' => $data['group_num'],
            'join_time' => time(),
            'end_time' => $data['end_time'],
        ]);

        Db::startTrans();
        try {

            // 提交事务
            Db::commit();
            return $group_order_id;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();

            return null;
        }
    }

    /**
     *
     * 新增交易信息
     * */
    public static function saveTradeInfo($group_order_id, $data)
    {
        $result = Db::name('group_order_trade')->insert([
            'store_id' => $data['store_id'],
            'group_order_id' => $group_order_id,
            'trade_method' => $data['payment_type'],
            'out_trade_no' => $data['out_trade_no'],
            'trade_fee' => $data['real_amount'],
            'trade_status' => -1,
        ]);

        return $result;

    }

    /**
     * 获取单规格活动商品信息
     * */
    public static function findSingleActivityGroupGoods($goods_id, $group_activity_id)
    {
        $goods = Db::name('group_goods')
            ->alias('a')
            ->field('a.id as group_goods_id,a.spec_type,c.group_activity_id,a.goods_name,a.main_image,a.market_price,a.sell_price,
                            a.group_price,a.stock,b.start_time,b.end_time,b.prepayment_amount,b.group_num,b.status')
            ->join('group_activity_goods c', 'c.group_goods_id=a.id')
            ->join('group_activity b', 'c.group_activity_id=b.id')
            ->where(['c.group_goods_id' => $goods_id, 'b.status' => 1, 'c.group_activity_id' => $group_activity_id])
            ->find();

        return $goods;
    }

    /**
     * 获取多规格商品信息
     * */
    public static function findManyActivityGroupGoods($sku_id, $group_activity_id)
    {
        $goods = Db::name('group_goods_item')
            ->field('a.group_goods_id,c.group_activity_id,b.goods_name,b.main_image,b.spec_type,a.attr,a.image,
                        a.market_price,a.sell_price,a.group_price,a.stock,
                        d.start_time,d.end_time,d.prepayment_amount,d.group_num,d.status')
            ->alias('a')
            ->join('group_goods b', 'a.group_goods_id=b.id')
            ->join('group_activity_goods c', 'c.group_goods_id=b.id')
            ->join('group_activity d', 'c.group_activity_id=d.id')
            ->where(['a.id' => $sku_id, 'b.status' => 1, 'c.group_activity_id' => $group_activity_id])
            ->find();
        // echo  Db::name('group_goods_item')->getLastSql();exit;
        return $goods;
    }

    /**
     * 获取单规格商品信息
     * */
    private static function findSingleGroupGoods($goods_id)
    {
        $goods = Db::name('group_goods')
            ->field('id as group_goods_id,spec_type,goods_name,main_image,market_price,sell_price,group_price,group_num,stock,status')
            ->where(['id' => $goods_id, 'status' => 1])
            ->find();

        return $goods;
    }

    /**
     * 获取多规格商品信息
     * */
    private static function findManyGroupGoods($sku_id)
    {
        $goods = Db::name('group_goods_item')
            ->field('a.group_goods_id,b.goods_name,b.main_image,b.spec_type,a.attr,a.image,
                    a.market_price,a.sell_price,a.group_price,a.stock,a.status')
            ->alias('a')
            ->join('group_goods b', 'a.group_goods_id=b.id')
            ->where(['a.id' => $sku_id, 'b.status' => 1])
            ->find();

        return $goods;
    }

    public static function findOrder($group_order_id)
    {
        $order = GroupOrder::withoutField('store_id,user_id')
            ->where('id', $group_order_id)
            ->with(['items'])
            // ->with(['items', 'address'])
            ->find();

        return $order;
    }

}
